<template>
    <n-form
        style="margin-top: 24px"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-placement="left"
        label-width="120"
        require-mark-placement="right-hanging"
    >

        <n-form-item label="资源类型" path="type">
            <n-select v-model:value="form.type" placeholder="请选择资源类型" :options="embeddingOptions" label-field="name"
                      value-field="sn" @update:value="handleTypeChange">
            </n-select>
        </n-form-item>
        <n-form-item label="资源名称" path="name">
            <n-input v-model:value="form.name" placeholder="请输入资源名称"></n-input>
        </n-form-item>
        <template v-for="item in items" :key="item.field">
            <!--      :required="item.required"-->
            <n-form-item
                :label="item.field=='defaultModel'?'大模型型号':item.field"
                :path="item.field"

            >
                <div v-if="item.field == 'dimension'" class="flex w-full">
                    <n-input
                        :default-value="item.defaultValue"
                        v-model:value="form[item.field]"
                        :disabled="item.readonly"
                        :placeholder="`请输入${item.field}`"
                    />
                    <jb-btn v-if="!item.defaultValue" icon="simple-icons:speedtest" type="primary" secondary style="margin-left: 8px" @click="handleTest">
                        获取
                    </jb-btn>
                </div>

                <div v-else class="flex-col w-full">

                    <n-input
                        :default-value="item.defaultValue"
                        :disabled="item.readonly"
                        v-model:value="form[item.field]"
                        :placeholder="`请输入${item.field=='defaultModel'?'大模型型号':item.field}${item.required?'':'，此项可以留空，系统会自动应用默认值'}`"
                    />
                    <span v-if="item.remark" class="text_tip">{{ item.remark }}</span>
                </div>

            </n-form-item>
        </template>

        <n-form-item label="请求频率限制">
            <n-space vertical>
                <n-input-group>
                    <n-input-number
                        v-model:value="rateLimitForm.minute"
                        :min="0"
                        placeholder="默认不限制"
                        style="width: 150px"
                        @update:value="handleRateLimitChange('minute')"
                    />
                    <n-input-group-label>/每分钟</n-input-group-label>
                </n-input-group>
                <n-input-group>
                    <n-input-number
                        v-model:value="rateLimitForm.hour"
                        :min="0"
                        placeholder="默认不限制"
                        style="width: 150px"
                        @update:value="handleRateLimitChange('hour')"
                    />
                    <n-input-group-label>/每小时</n-input-group-label>
                </n-input-group>
                <n-input-group>
                    <n-input-number
                        v-model:value="rateLimitForm.day"
                        :min="0"
                        placeholder="默认不限制"
                        style="width: 150px"
                        @update:value="handleRateLimitChange('day')"
                    />
                    <n-input-group-label>/每天</n-input-group-label>
                </n-input-group>
            </n-space>
        </n-form-item>
    </n-form>
</template>

<script setup>
import {onMounted, reactive, ref, watch} from 'vue'
import {JBoltApi} from '@/service/request'
import {toJSONString} from 'xe-utils'
import {useResetableData} from "@/hooks/common/use-resetable-data.js";

const props = defineProps({
    id: {
        type: String
    }
})


const formRef = ref(null)
const items = ref(null)

const form = ref({
    id: '',
    name: '',
    type: null,
    apiKey: null,
    defaultModel: '',
    apiSecret: '',
    apiUrl: '',
    limits: '',
    dimension: "",
    enable: true,
    createTime: '',
})

const rateLimitForm = reactive({
    minute: null,
    hour: null,
    day: null
})

const rules = reactive(
    {
        type: {
            required: true,
            message: '请选择资源类型',
            trigger: 'change'
        },
        name: {
            required: true,
            message: '请输入资源名称',
            pattern: /\S/, // 至少有一个非空白字符
            trigger: 'change'
        }
    }
)

// 动态添加验证规则
watch(() => items.value, (newItems) => {
    if (newItems) {
        form.value = {
            id: form.value.id,
            name: form.value.name,
            type: form.value.type,
            apiKey: form.value.apiKey,
            apiSecret: form.value.apiSecret,
            apiUrl: form.value.apiUrl,
            limits: '',
            // dimension: "",
            dimension: form.value.dimension,
            defaultModel: form.value.defaultModel,
            enable: form.value.enable,
            createTime: '',
        }
        newItems.forEach(item => {
            if (item.required) {
                rules[item.field] = {
                    required: true,
                    pattern: /\S/, // 至少有一个非空白字符
                    message: `请输入${item.field}`,
                    trigger: 'blur'
                }
            }else {
                delete rules[item.field]
            }

            if (item.field == 'dimension' && item.defaultValue) {
                form.value[item.field] = item.defaultValue
            }
        })
    }
}, {immediate: true, deep: true})

function handleTest() {

    JBoltApi.tryPost('/embeddingResource/getModelDimension', {
        ...form.value,
        defaultModel: form.value.defaultModel
    }).then(res => {
        form.value.dimension = res.data;
    }).catch((error) => {
        console.error(error)
    })

}

// 处理频率限制变化
function handleRateLimitChange(unit) {
    const limits = []
    if (rateLimitForm.minute > 0) {
        limits.push({unit: 'minute', times: rateLimitForm.minute})
    }
    if (rateLimitForm.hour > 0) {
        limits.push({unit: 'hour', times: rateLimitForm.hour})
    }
    if (rateLimitForm.day > 0) {
        limits.push({unit: 'day', times: rateLimitForm.day})
    }
    form.value.limits = JSON.stringify(limits)
}

// 加载编辑数据时解析频率限制
function parseLimits(limitsStr) {
    if (!limitsStr) return
    try {
        const limits = JSON.parse(limitsStr)
        limits.forEach(limit => {
            rateLimitForm[limit.unit] = limit.times
        })
    } catch (error) {
        console.error('解析频率限制失败:', error)
    }
}

// 加载编辑数据
async function loadEditData() {
    if (props.id) {
        const {result} = await JBoltApi.get(`/embeddingResource/getById/${props.id}`)
        form.value = result.data
        if (form.value.type) {
            const selectedModel = embeddingOptions.value.find(item => item.sn === form.value.type)
            if (selectedModel) {
                items.value = selectedModel.configItems
            }
        }
        // 解析频率限制
        parseLimits(result.data.limits)
    }
}

defineExpose({
    submit
})

async function submit(fun) {
    await formRef.value?.validate()
    let url = props.id ? '/embeddingResource/update' : '/embeddingResource/add'

    await JBoltApi.tryPost(url, form.value)


    if (fun) {
        fun()
    }

    return true
}

const embeddingOptions = ref([])

function handleTypeChange(value) {

    const selectedModel = embeddingOptions.value.find(item => item.sn === value)
    if (selectedModel) {

        items.value = selectedModel.configItems

    }
}

function loadModelTypeList() {
    JBoltApi.tryGet('/embeddingModelType/list').then(res => {
        embeddingOptions.value = res.data

        loadEditData()
    }).catch((error) => {
        console.error(error)
    })
}

onMounted(() => {
    loadModelTypeList()
})

</script>

<style scoped lang="scss">
.text_tip {
    font-size: 12px;
    color: #999;
}
</style>